package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.AdminDTO;
import com.sky.dto.AdminLoginDTO;
import com.sky.entity.Admin;
import com.sky.exception.BaseException;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.AdminMapper;
import com.sky.service.AdminService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import static com.sky.constant.MessageConstant.*;
import static com.sky.constant.PasswordConstant.DEFAULT_PASSWORD;

@Service
@Slf4j
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

	private final AdminMapper adminMapper;

	@Override
	public Admin login(AdminLoginDTO adminLoginDTO) {
		String username = adminLoginDTO.getUsername();
		String password = adminLoginDTO.getPassword();

		// 校验用户名和密码是否为空
		if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
			throw new LoginFailedException(USERNAME_OR_PASSWORD_IS_EMPTY);
		}

		// 校验用户是否存在
		LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<Admin>()
														 .eq(Admin::getUsername, username);
		if (adminMapper.selectCount(queryWrapper) != 1) {
			throw new LoginFailedException(ACCOUNT_NOT_FOUND);
		}

		// 校验密码是否正确
		Admin admin = adminMapper.selectOne(queryWrapper);
		password = DigestUtils.md5DigestAsHex(password.getBytes());
		if (!StrUtil.equals(password, admin.getPassword())) {
			throw new LoginFailedException(PASSWORD_ERROR);
		}

		return admin;
	}

	@Override
	public void add(AdminDTO adminDTO) {
		// 先看看用户名是否存在
		LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Admin::getUsername, adminDTO.getUsername());
		if (adminMapper.selectCount(queryWrapper) > 0) {
			throw new LoginFailedException(USER_ALREADY_EXISTS);
		}

		Admin admin = new Admin();
		admin.setUsername(adminDTO.getUsername());
		admin.setPassword(DigestUtils.md5DigestAsHex(DEFAULT_PASSWORD.getBytes()));
		admin.setName(adminDTO.getName());
		admin.setPhone(adminDTO.getPhone());
		admin.setSex(adminDTO.getSex());

		adminMapper.insert(admin);
	}

	@Override
	public void update(AdminDTO adminDTO) {
		Long id = adminDTO.getId();
		if (id == null) {
			throw new BaseException(ID_IS_NULL);
		}

		// 检查一下是否存在
		if (!this.exists(new LambdaQueryWrapper<Admin>().eq(Admin::getId, id))) {
			throw new BaseException(ACCOUNT_NOT_FOUND);
		}

		Admin admin = new Admin();
		admin.setId(id);
		admin.setName(adminDTO.getName());
		admin.setPhone(adminDTO.getPhone());
		admin.setSex(adminDTO.getSex());
		adminMapper.updateById(admin);
	}
}
